package sk.upjs.ariadne.editor.maplayers;

import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.filechooser.FileFilter;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;

public class ImageLayerControlPanel extends JPanel {

	private static class ImageFilter extends FileFilter {

		@Override
		public boolean accept(File f) {
			if (f.isDirectory()) {
				return true;
			}

			String ext = f.getName()
					.substring(f.getName().lastIndexOf('.') + 1);

			if ("jpg".equals(ext) || "png".equals(ext))
				return true;

			return false;
		}

		@Override
		public String getDescription() {
			return "Image files";
		}

	}

	/**
	 * Layer that is controlled by this panel.
	 */
	private ImageLayer layer;

	/**
	 * Create the panel.
	 */
	public ImageLayerControlPanel(ImageLayer layer) {
		this.layer = layer;
		JButton btnChooseImage = new JButton("Choose image ...");
		btnChooseImage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openChooseImageDialog();
			}
		});
		GroupLayout groupLayout = new GroupLayout(this);
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(
				Alignment.LEADING).addGroup(
				groupLayout.createSequentialGroup()
						.addComponent(btnChooseImage)
						.addContainerGap(723, Short.MAX_VALUE)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(
				Alignment.LEADING).addGroup(
				groupLayout.createSequentialGroup()
						.addComponent(btnChooseImage)
						.addContainerGap(61, Short.MAX_VALUE)));
		setLayout(groupLayout);
	}

	/**
	 * Opens a dialog for choosing an image that is displayed in this layer.
	 */
	private void openChooseImageDialog() {
		JFileChooser fc = new JFileChooser();
		fc.setFileFilter(new ImageFilter());
		int returnVal = fc.showOpenDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			layer.loadImage(fc.getSelectedFile());
		}
	}
}
